1 package org.apache.maven.surefire.junitcore.pc;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import java.util.concurrent.Semaphore;
23
24 /**
25 * @author Tibor Digana (tibor17)
26 * @see Balancer
27 * @since 2.16
28 */
29 final class ThreadResourcesBalancer
30 implements Balancer
31 {
32 private final Semaphore balancer;
33
34 private final int numPermits;
35
36 /**
37 * <tt>fair</tt> set to false.
38 *
39 * @param numPermits number of permits to acquire when maintaining concurrency on tests.
40 * Must be >0 and < {@link Integer#MAX_VALUE}.
41 * @see #ThreadResourcesBalancer(int, boolean)
42 */
43 ThreadResourcesBalancer( int numPermits )
44 {
45 this( numPermits, false );
46 }
47
48 /**
49 * @param numPermits number of permits to acquire when maintaining concurrency on tests.
50 * Must be >0 and < {@link Integer#MAX_VALUE}.
51 * @param fair <tt>true</tt> guarantees the waiting schedulers to wake up in order they acquired a permit
52 * @throws IllegalArgumentException if <tt>numPermits</tt> is not positive number
53 */
54 ThreadResourcesBalancer( int numPermits, boolean fair )
55 {
56 if ( numPermits <= 0 )
57 {
58 throw new IllegalArgumentException(
59 String.format( "numPermits=%d should be positive number", numPermits ) );
60 }
61 balancer = new Semaphore( numPermits, fair );
62 this.numPermits = numPermits;
63 }
64
65 /**
66 * Acquires a permit from this balancer, blocking until one is available.
67 *
68 * @return <code>true</code> if current thread is <em>NOT</em> interrupted
69 * while waiting for a permit.
70 */
71 public boolean acquirePermit()
72 {
73 try
74 {
75 balancer.acquire();
76 return true;
77 }
78 catch ( InterruptedException e )
79 {
80 return false;
81 }
82 }
83
84 /**
85 * Releases a permit, returning it to the balancer.
86 */
87 public void releasePermit()
88 {
89 balancer.release();
90 }
91
92 public void releaseAllPermits()
93 {
94 balancer.release( numPermits );
95 }
96 }